﻿using IdentityModel;
using IdentityServer4.Validation;
using OAuth.Server.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace OAuth.Server.OAuth
{
    public class OwnerValidator: IResourceOwnerPasswordValidator
    {
        private readonly IAccountRepository _repository;

        public OwnerValidator(UowAccountRepository repository)
        {
            _repository = repository;
        }

        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            var user = await _repository.Login(context.UserName, context.Password);

            var claims = new List<Claim>
            {
                new Claim(JwtClaimTypes.PhoneNumber,user.Mobile),
                new Claim(JwtClaimTypes.PhoneNumberVerified,((user.EncryptionType & 2)>0).ToString()),
                new Claim(JwtClaimTypes.Email,user.Email),
                new Claim(JwtClaimTypes.EmailVerified,((user.EncryptionType & 2)>0).ToString())
            };
            context.Result = new GrantValidationResult(user.Id.ToString(), user.UserName, claims);
        }
    }
}
